package com.apkplug.cloudservicedemo.activity;

import java.util.ArrayList;
import java.util.List;
import org.apkplug.app.FrameworkInstance;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import com.apkplug.cloudservicedemo.ProxyApplication;
import com.apkplug.cloudservicedemo.R;
import com.apkplug.service.ApkplugCloudAgent;
import com.apkplug.service.SearchApp.*;
import com.apkplugdemo.adapter.SearchBundleAdapter;
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.Toast;

public class SearchActivity extends ListActivity {
	private FrameworkInstance frame=null;
	private appSearchBean bean=null;
	private SearchBundleAdapter adapter;

    private ArrayList<appBean> apps = null;

    /** Called when the activity is first created. */
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.launcher);
        frame=((ProxyApplication)this.getApplication()).getFrame();
        apps = new ArrayList<appBean>();
        updataDate(frame.getSystemBundleContext());
        adapter = new SearchBundleAdapter(SearchActivity.this,frame.getSystemBundleContext(),apps);
        setListAdapter(adapter);
    }
	public void updataDate(BundleContext context){
		appSearchBean bean=new appSearchBean();
		//按插件被添加到分组(宿主)的时间逆序查询
    	bean.setG_order(appSearchBean.order_desc);
    	//插件的关键词keyword
    	//bean.setB_keywords("工具");
    	bean.setPagenum(10);
    	bean.setPage(0);
	    //查询
    	ApkplugCloudAgent.getAppSearch().search(bean,new impAppSearchCallBack());
	}
	
	/**
	 * 查询回调接口
	 * @author 梁前武
	 *
	 */
   class impAppSearchCallBack implements AppSearchCallBack{
	   public void onFailure(int arg0, final String arg1) {
		   //服务查询失败
			SearchActivity.this.runOnUiThread(new Runnable(){
				public void run() {
					Toast.makeText(SearchActivity.this, arg1,
				     Toast.LENGTH_SHORT).show();
				}
			});	
		}
		public void onSuccess(int stutas, CallBackMSG msg,appSearchBean arg2) {
			//服务查询成功
			if(stutas>=0){
				if(msg.getStutes()>=0){
					//获取查询到的插件
					List<appBean> aps=(List)msg.getMsg();
					if(aps.size()==0){
						SearchActivity.this.runOnUiThread(new Runnable(){
							public void run() {
								Toast.makeText(SearchActivity.this, "没有找到这种类型的插件",
							     Toast.LENGTH_SHORT).show();
							}
						});	
					}
					for (int i = 0; i < aps.size(); i++) {
						appBean ab=aps.get(i);
   						apps.add(ab);
   				 	}
					//更新列表
   				 	SearchActivity.this.runOnUiThread(new Runnable(){
   				 		public void run(){
   						 adapter.notifyDataSetChanged();
   				 		}
   				 	});
				}
			}else{
				SearchActivity.this.runOnUiThread(new Runnable(){
					public void run() {
						Toast.makeText(SearchActivity.this, "网络连接错误",
					     Toast.LENGTH_SHORT).show();
					}
				});	
			}
		}  
   }

}
